/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jbsa.admin.controller.system;

import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;

import cn.hg.jbsa.admin.controller.BaseJbsaAdminController;
import cn.hg.jbsa.admin.model.JbsaAdmin;
import cn.hg.jbsa.admin.model.JbsaOption;
import cn.hg.jbsa.admin.service.JbsaOptionService;
import cn.hg.jbsa.common.annotation.JbsaLog;
import cn.hg.jbsa.common.constant.JbsaConstants;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import io.jboot.components.cache.annotation.CacheEvict;
import io.jboot.db.model.Columns;
import io.jboot.web.controller.annotation.GetRequest;
import io.jboot.web.controller.annotation.PutRequest;
import io.jboot.web.controller.annotation.RequestMapping;

/**
 * @author Golly
 */
@RequestMapping(value = "/admin/system/option")
public class JbsaOptionController extends BaseJbsaAdminController {

    @Inject
    private JbsaOptionService optionService;

    /**
     * 跳转到列表页面
     */
    @Override
    @GetRequest
    @RequiresPermissions(value = {"system:option:view"})
    public void index () {
    }

    @PutRequest
    @CacheEvict(name = JbsaConstants.CACHE_NAME_OPTION)
    @RequiresPermissions(value = {"system:option:edit"})
    @JbsaLog("更新系统设置")
    public void save () {
        JbsaAdmin admin = this.getCurrentAdmin();
        Date now = new Date();

        Kv data = this.getKv();

        for (Object paraKey : data.keySet()) {
            List<String> splitKey = CharSequenceUtil.split((String) paraKey, '.');
            if (splitKey.size() != 2) {
                continue;
            }
            String type = splitKey.get(0);
            String key = splitKey.get(1);
            String value = data.getStr(paraKey);

            JbsaOption option = this.optionService.findFirstByColumns(Columns.create("type", type).eq("key", key));

            if (ObjectUtil.isNull(option)) {
                continue;
            }

            if (!CharSequenceUtil.equals(value, option.getValue())) {
                option.setValue(value);
                option.setEditedTime(now);
                option.setEditorId(admin.getId());

                this.optionService.update(option);
            }
        }

        this.renderAjaxSuccessed();
    }

}
